package com.yupi.yu_picture.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.yupi.yu_picture.exception.BusinessException;
import com.yupi.yu_picture.exception.ErrorCode;
import com.yupi.yu_picture.exception.ThrowUtil;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;

import java.net.URL;
import java.util.Arrays;
import java.util.List;

@Service
public class UrlPictureUpload extends PictureUploadTemplate{

    @Override
    protected void validPicture(Object inputSource) {
        String url=(String)inputSource;
        ThrowUtil.throwIf(StrUtil.isBlank(url), ErrorCode.PARAMS_ERROR, "文件地址不能为空");
        //1.校验url格式，通过Java自带的url类构造，如果该url不合法就会抛出一个异常
        try {
            new URL(url);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件地址不正确");
        }
        //2.校验url协议：
        ThrowUtil.throwIf(!(url.startsWith("http://")||url.startsWith("https://")),ErrorCode.PARAMS_ERROR,"文件地址不正确");

        //3.发送 HEAD 请求以验证文件是否存在
        HttpResponse response=null;
        try{
            response = HttpUtil.createRequest(Method.HEAD, url).execute();
            if (response.getStatus()!= HttpStatus.HTTP_OK){
                return;
            }
            //4.校验文件类型
            String contentType = response.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)){
                // 允许的图片类型
                //当遇到这种类型比较少的东西的时候，可以有一个集合把它装起来，任何看有没有在集合中
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                boolean contains = ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase());
                ThrowUtil.throwIf(!contains,ErrorCode.PARAMS_ERROR,"文件类型错误");

            }
            //5.校验文件大小
            String contentLengthStr = response.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)) {
                try {
                    long contentLength = Long.parseLong(contentLengthStr);
                    final long TWO_MB = 2 * 1024 * 1024L; // 限制文件大小为 2MB
                    ThrowUtil.throwIf(contentLength > TWO_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }
            }
        }finally {
            if (response!=null){
                response.close();
            }
        }

    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        String url=(String)inputSource;
        return FileUtil.mainName(url);
    }

    @Override
    protected void processFile(Object inputSource, File file) throws Exception {
        String url=(String)inputSource;
        HttpUtil.downloadFile(url,file);
    }
}
